<script setup lang="ts">
/**
 * 导出数据
 */
import { ref, nextTick } from "vue";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { useSendCode } from "@/hook/useSendCode";
import { sendSms } from "@/api";
import { message } from "@/utils/message";
import ShieldKeyholeLine from "@iconify-icons/ri/shield-keyhole-line";

const { isSend, codeText, onSendCode, adminPhone } = useSendCode();

defineProps({
  /**
   * 是否使用短信模板
   */
  sms: {
    type: Boolean,
    default: () => true
  }
});
const form = ref({
  verificationCode: null
});
const smsRef = ref();
/**
 * ref
 */
const ruleFormRef = ref();
function getRef() {
  return ruleFormRef.value;
}
/**
 * 表单值
 */
function getFormData() {
  return form.value;
}
/**
 * 发送验证码
 */
const loading = ref(false);
async function onSendCodeHandler() {
  if (loading.value) return;
  if (isSend.value) {
    message(`验证码已发送，${codeText.value}后再发送`, { type: "error" });
    return;
  }
  loading.value = true;
  const par = {
    action: {
      phone: adminPhone,
      smsTemplate: "DATA_EXPORT"
    }
  };
  const res = await sendSms(par);
  loading.value = false;
  if (!res.success) {
    message(res.info, { type: "error" });
    return;
  }
  onSendCode();
  message("发送成功", { type: "success" });
  onInputFocus();
}
function onInputFocus() {
  nextTick(() => {
    smsRef.value.focus();
  });
}
/**
 * 弹窗 表单所需的ref
 */
defineExpose({
  getRef,
  getFormData,
  onInputFocus
});
</script>

<template>
  <div>
    <el-form
      ref="ruleFormRef"
      label-width="120px"
      label-position="left"
      :model="form"
      class="search-form"
    >
      <p v-if="sms" class="mb-[20px]">
        导出数据需要管理员手机号验证，验证码将会下发到手机号
        <span class="text-red">{{ adminPhone }}</span>
      </p>
      <el-form-item
        label="验证码："
        prop="verificationCode"
        :rules="[
          {
            required: true,
            message: '请输入验证码'
          }
        ]"
      >
        <el-input
          ref="smsRef"
          v-model="form.verificationCode"
          clearable
          :type="sms ? 'text' : 'password'"
          :show-password="!sms"
          placeholder="请输入验证码"
          :prefix-icon="useRenderIcon(ShieldKeyholeLine)"
        >
          <template v-if="sms" #append>
            <el-button
              :loading="loading"
              type="primary"
              @click="onSendCodeHandler"
            >
              {{ isSend ? `已发送(${codeText})` : "获取验证码" }}
            </el-button>
          </template>
        </el-input>
      </el-form-item>
    </el-form>
  </div>
</template>

<style lang="scss" scoped>
.search-form {
  .tip {
    margin-bottom: 10px;
    color: red;
  }

  .copy {
    margin-left: 10px;
    color: var(--el-color-primary);
    cursor: pointer;
  }
}
</style>
